<script setup lang="tsx">
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { GetCoursePlanStatisticsApi, PalyVideoApi } from '@/api/course'
import { ref, unref, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { AnalysisItem, AnalysisItem_Zh, SpanMethodProps, VideoDt } from '@/api/course/type'
import * as XLSX from 'xlsx'
import { useButtonPermiss } from '@/utils/buttonpermiss'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import lookVideos from '@/views/examination/components/lookVideos.vue'
import { createImageViewer } from '@/components/ImageViewer'
const { t } = useI18n()

const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const lookimg = (url) => {
  createImageViewer({
    urlList: [url]
  })
}
const dialogVisible = ref(false)
const videoList = ref<VideoDt[]>([])
const columns2: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },

  {
    field: 'courseName',
    label: '课程名称'
  },
  {
    field: 'planCount',
    label: '课程数量'
  },
  {
    field: 'videoTimes',
    label: '课程时长'
  },
  {
    field: 'teacherUserName',
    label: '老师'
  },

  {
    field: 'userNames',
    label: '学员'
  },

  {
    field: 'planTime',
    label: '培训时间'
  },

  {
    field: 'videoTime',
    label: '视频总时长'
  },
  {
    field: 'videos',
    label: '视频',
    slots: {
      default: (data: any) => {
        let videoPath = data.row.videos
        return (
          <>
            {videoPath ? (
              <BaseButton
                type="primary"
                onClick={() => {
                  dialogVisible.value = true
                  videoList.value = videoPath.map((item: any) => {
                    let videoLength = item.videoTime
                    let hour = parseInt(videoLength / 3600 + '')
                    let minute = parseInt((videoLength % 3600) / 60 + '')
                    let second = parseInt((videoLength % 60) + '')
                    return {
                      ...item,
                      videoTime: `${hour}小时${minute}分钟${second}秒`
                    }
                  })
                }}
              >
                查看
              </BaseButton>
            ) : null}
          </>
        )
      }
    }
  }
]

const handleTime = (time: number) => {
  let hour = parseInt(time / 3600 + '')
  let minute = parseInt((time % 3600) / 60 + '')
  let second = parseInt((time % 60) + '')
  return time ? `${hour}小时${minute}分钟${second}秒` : ''
}

let list: AnalysisItem[] = []
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState

    const res = await GetCoursePlanStatisticsApi({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      ...unref(searchParams)
    })
    list = []
    res.data.map((item) => {
      item.planInfos?.map((nitem) => {
        let { courseName, planCount, videoTime } = item
        let userNames = ''

        JSON.parse(nitem.planUsers)?.map((uitem) => {
          userNames += `${uitem.UserName}、`
        })
        userNames = userNames.slice(0, userNames.length - 1)
        list.push({
          courseName,
          planCount,
          videoTimes: handleTime(videoTime),
          ...nitem,
          videoTime: handleTime(nitem.videoTime),
          userNames
        })
      })
    })
    console.log('------------', list)
    return {
      list: list,
      total: res.data.courseCount || 0
    }
  }
})
const teacherSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
    // 当前列为0的时候不进行操作单元格
    const name = row[column.property]
    const preRow = list[rowIndex - 1]
    const preValue = preRow ? preRow[column.property] : null
    if (name === preValue) {
      return { rowspan: 0, colspan: 0 } // 不生成单元格
    } else {
      let rowspan = 1
      for (let i = rowIndex + 1; i < list.length; i++) {
        const nextRow = list[i]
        const nextValue = nextRow[column.property]
        if (nextValue === name) {
          rowspan++
        } else {
          break
        }
      }
      return { rowspan, colspan: 1 }
    }
  }
}
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'userName',
    label: '老师',
    component: 'Input'
  },
  {
    field: 'courseName',
    label: '课程',
    component: 'Input'
  },

  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])

const handleData = () => {
  let arr: AnalysisItem_Zh[] = []

  list.map((item) => {
    arr.push({
      课程名称: item.courseName,
      课程数量: item.planCount,
      课程时长: item.videoTimes,
      讲师: item.teacherUserName,
      学员: item.userNames,
      培训时间: item.examTime,
      视频总时长: item.videoTime + '',
      视频名称: item?.videos?.map((video) => video.videoName).join(', ') || '',
      视频地址: item?.videos?.map((video) => video.videoPath).join(', ') || ''
    })
  })
  return arr
}
const exportToExcel = async () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '课程培训统计分析.xlsx')
}
</script>

<template>
  <div>
    <div style="display: flex; justify-content: space-between; margin-bottom: 10px">
      <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
      <BaseButton type="primary" @click="exportToExcel()" v-if="haspermiss.includes('导出')">{{
        t('exampleDemo.exprot')
      }}</BaseButton>
    </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="columns2"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :max-height="600"
      :span-method="teacherSpanMethod"
    />
    <!--  -->
    <Dialog v-model="dialogVisible" title="视频" :fullscreen="false">
      <lookVideos :videoList="videoList" />
      <template #footer>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style>
.clome {
  display: flex;
  flex-direction: column;
}
.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 24px;
}
.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 10px;
}
</style>
